package com.lancoo.tyjx.multichatroom.xmpp;

import android.content.Intent;
import android.util.Log;

import com.lancoo.tyjx.multichatroom.activity.MyApplication;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.db.MsgDbHelper;
import com.lancoo.tyjx.multichatroom.db.NewMsgDbHelper;
import com.lancoo.tyjx.multichatroom.model.ChatItem;
import com.lancoo.tyjx.multichatroom.model.NoticeEvent;
import com.lancoo.tyjx.multichatroom.model.Room;
import com.lancoo.tyjx.multichatroom.utils.DateUtil;
import com.lancoo.tyjx.multichatroom.utils.FileUtil;
import com.lancoo.tyjx.multichatroom.utils.JsonUtil;
import com.lancoo.tyjx.multichatroom.utils.MyAndroidUtil;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Message.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.packet.DelayInformation;


public class XmppMessageListener implements PacketListener {

    private static final String TAG = "XmppMessageListener";

    @Override
    public void processPacket(Packet packet) {
        final Message nowMessage = (Message) packet;
        if (Constants.IS_DEBUG) {
            Log.e("xmppchat come", nowMessage.toXML());
        }

        if (nowMessage.toXML().contains("<invite")) {
            String noti = "你被邀请加入群组" + XmppTool.getRoomName(nowMessage.getFrom());
            MyAndroidUtil.showNoti(noti);
            String userName = XmppTool.getRoomName(nowMessage.getFrom());
            ChatItem msg = new ChatItem(ChatItem.GROUP_CHAT, userName, userName, "", noti, DateUtil.now_MM_dd_HH_mm_ss(), 0, 1);
            NewMsgDbHelper.getInstance(MyApplication.getInstance()).saveNewMsg(userName);
            MsgDbHelper.getInstance(MyApplication.getInstance()).saveChatMsg(msg);
            MyApplication.getInstance().sendBroadcast(new Intent("ChatNewMsg"));

            XmppTool.getInstance().joinMultiUserChat(Constants.USER_NAME, XmppTool.getRoomName(nowMessage.getFrom()), true);
        }


        Type type = nowMessage.getType();
        if ((type == Type.groupchat || type == Type.chat)
                && !nowMessage.getBody().equals("")) {
            String chatName = "";
            String userName = "";
            int chatType = ChatItem.CHAT;

            //name
            if (type == Type.groupchat) {
                chatName = XmppTool.getRoomName(nowMessage.getFrom());
                userName = XmppTool.getRoomUserName(nowMessage.getFrom());
                chatType = ChatItem.GROUP_CHAT;
            } else {
                chatName = userName = XmppTool.getUsername(nowMessage.getFrom());
            }

            if (!userName.equals(Constants.USER_NAME)) {  //不是自己发出的,防群聊
                //time

                DelayInformation inf = (DelayInformation) nowMessage.getExtension("x",
                        "jabber:x:delay");
//                if (inf == null) {
//                    dateString = DateUtil.now_MM_dd_HH_mm_ss();
//                } else {
//                    dateString = DateUtil.dateToStr_MM_dd_HH_mm_ss(inf.getStamp());
//                }

                //msg
                ChatItem msg = null;
                //消息json body
                String msgBody = null;
                int audiotime = 0;
                String msgType = JsonUtil.whatMsgType(nowMessage.getBody());
                //消息实际内容
                String msgContent = JsonUtil.json2XmppMsg(nowMessage.getBody());
                String dateString = JsonUtil.getSendTime(nowMessage.getBody());

                if (msgContent.equals("No supported")) {
                    Log.e(TAG, "不支持此信息");
                    return;
                }

                String msgHeaderImg = JsonUtil.json2XmppMsgHeaderImg(nowMessage.getBody());// 获取头像地址
                String fileName = null;
                String fileUrl = null;

                if (msgType.equalsIgnoreCase("like")) {
                    if (msgContent.equalsIgnoreCase("like")) {
                        msgBody = "对本堂课{点赞}";
                    } else {
                        msgBody = "对本堂课{取消点赞}";
                    }
                }
                // 文件
                else if (msgType.equalsIgnoreCase("file")) {
                    fileUrl = JsonUtil.getFileUrl(nowMessage.getBody());
                    fileName = JsonUtil.getFileName(nowMessage.getBody());
                }
                //
                else if (msgType.equalsIgnoreCase("notice")) {
                    EventBus.getDefault().post(new NoticeEvent(msgContent));
                    return;
                } else if (nowMessage.getProperty("imgData") != null) { //判断是否图片
                    if (FileUtil.getType(msgContent) == FileUtil.SOUND) {
                        msgBody = Constants.SAVE_SOUND_PATH + "/" + msgContent;
                    } else {
                        msgBody = Constants.SAVE_IMG_PATH + "/" + msgContent;
                    }
                    FileUtil.saveFileByBase64(nowMessage.getProperty("imgData").toString(), msgBody);
                } else if (nowMessage.getType() == Type.groupchat
                        & msgContent.contains(":::")) { //语音
                    String[] msgAndData = msgContent.split(":::");
                    if (FileUtil.getType(msgAndData[0]) == FileUtil.SOUND) {
                        msgBody = Constants.SAVE_SOUND_PATH + "/" + msgAndData[0];
                        audiotime = JsonUtil.getAudioTime(nowMessage.getBody());
                    } else {
                        msgBody = Constants.SAVE_IMG_PATH + "/" + msgAndData[0];
                    }
                    FileUtil.saveFileByBase64(msgAndData[1], msgBody);
                } else {
                    msgBody = msgContent;
                }

                if (type == Type.groupchat && XmppTool.leaveRooms.contains(new Room(chatName))) {  //正常保存了
                    System.out.println("我已经离开这个房间了");
                } else if (msgContent.contains("[RoomChange")) {
//					String leaveRoom = nowMessage.getBody().split(",")[1];
//					String leaveUser = nowMessage.getBody().split(",")[2];
//					XmppConnection.getInstance().getMyRoom()
//					.get(XmppConnection.getInstance().getMyRoom().indexOf(new Room(leaveRoom))).friendList.remove(leaveUser);
//					XmppTool.getInstance().reconnect();
                } else {
                    String usName;
                    try {
                        usName = userName.split("&")[2];
                    } catch (Exception e) {
                        usName = userName.split("&")[1];
                        e.printStackTrace();
                    }
                    msg = new ChatItem(chatType, chatName, usName, msgHeaderImg, msgBody, dateString, 0, 1);
                    msg.setVoicetime(audiotime);
                    msg.setFileUrl(fileUrl);
                    msg.setFileName(fileName);
                    msg.setMsgType(msgType);
                    NewMsgDbHelper.getInstance(MyApplication.getInstance()).saveNewMsg(chatName);
                    if (!MsgDbHelper.getInstance(MyApplication.getInstance()).isExist(msg)) {
                        MsgDbHelper.getInstance(MyApplication.getInstance()).saveChatMsg(msg);
                        MyApplication.getInstance().sendBroadcast(new Intent("ChatNewMsg"));
                        MyAndroidUtil.showNoti(msgBody);
                    }
                }
            }
        }
    }
}
